package com.joysuch.wwyt.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.common.bean.CommonStaticsReportBean;
import com.joysuch.wwyt.common.bean.CommonStaticsReportDetailBean;
import com.joysuch.wwyt.common.entity.CommonStaticsReport;
import com.joysuch.wwyt.common.enums.CommonStaticsModuleTypes;
import com.joysuch.wwyt.common.repository.CommonStaticsReportDao;
import com.joysuch.wwyt.common.service.CommonStaticsReportService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.support.Context;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author ZhangDong
 * @Date 2020/7/23 14:13
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class CommonStaticsReportServiceImpl implements CommonStaticsReportService {

    @Autowired
    private CommonStaticsReportDao dao;

    @Override
    public ResultBean save(CommonStaticsReportBean bean) {
        Subject subject = SecurityUtils.getSubject();
        if (bean.getAllUserFlag() == 1) {
            Assert.isTrue(subject.hasRole("管理员") || Context.getCurrentUser().isSuperAdmin(), "只有管理员可配置全局");
        }
        Long id = bean.getId();
        List<CommonStaticsReportDetailBean> chartList = bean.getChartList();
        if (chartList != null) {
            for (CommonStaticsReportDetailBean detailBean : chartList) {
                Integer chartId = detailBean.getChartId();
                if (chartId != null && !supportModule(chartId)) {
                    return ResultBean.fail(101, "not support this chartId:" + detailBean.getChartId());
                }
            }
        }
        Long currentUserId = Context.getCurrentUserId();
        Integer allUserFlag = bean.getAllUserFlag();
        CommonStaticsReport staticsReport;
        if (id == null) {
            Integer exist = existTitleJudge(bean.getTitle(), currentUserId, allUserFlag);
            if (exist != null) {
                return ResultBean.fail(101, "此标题已存在");
            }
            staticsReport = new CommonStaticsReport();
            staticsReport.setState(DataStateTypes.EFFECTIVE.getState());
        } else {
            staticsReport = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
            if (DataStateTypes.UN_EFFECTIVE.getState().equals(staticsReport.getState())) {
                return ResultBean.fail(101, "此数据已作废");
            }
            if (!bean.getTitle().equals(staticsReport.getTitle())) {
                Integer exist = existTitleJudge(bean.getTitle(), currentUserId, allUserFlag);
                if (exist != null) {
                    return ResultBean.fail(101, "此标题已存在");
                }
            }
        }
        BeanUtils.copyProperties(bean, staticsReport);
        staticsReport.setChartList(chartList == null ? null : JSON.toJSONString(chartList));
        staticsReport.setUserId(currentUserId);
        CommonStaticsReport save = dao.save(staticsReport);
        return ResultBean.success(save.getId());
    }

    @Override
    public ResultBean delete(Long id) {
        Assert.notNull(id, "id cannot be null");
        CommonStaticsReport report = getById(id);
        if (DataStateTypes.UN_EFFECTIVE.getState().equals(report.getState())) {
            return ResultBean.fail(101, "此数据已作废");
        }
        report.setState(DataStateTypes.UN_EFFECTIVE.getState());
        dao.save(report);
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public ResultBean list() {
        //查个人和全局
        Long currentUserId = Context.getCurrentUserId();
        List<CommonStaticsReport> list = dao.queryByUserId(currentUserId);
        list.addAll(dao.queryByAllUser());
        return ResultBean.success(list.stream().map(CommonStaticsReportBean::new).collect(Collectors.toList()));
    }

    @Override
    public ResultBean get(Long id) {
        Assert.notNull(id, "id cannot be null");
        CommonStaticsReport report = getById(id);
        if (DataStateTypes.UN_EFFECTIVE.getState().equals(report.getState())) {
            return ResultBean.fail(101, "此数据已作废");
        }
        return ResultBean.success(new CommonStaticsReportBean(report));
    }

    public CommonStaticsReport getById(Long id) {
        return dao.findById(id).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
    }

    private Integer existTitleJudge(String title, Long currentUserId, Integer allUserFlag) {
        if (allUserFlag == 0) {
            return dao.existByTitle(title, currentUserId, allUserFlag);
        }
        return dao.existByTitle(title, null, allUserFlag);
    }

    private static boolean supportModule(Integer index) {
        return CommonStaticsModuleTypes.getModule(index) == null ? false : true;
    }
}
